package com.example.demo.controller;

import com.example.demo.config.Interceptor.PassToken;
import com.example.demo.config.Interceptor.Role;
import com.example.demo.dao.User;
import com.example.demo.service.impl.Userserviceimpl;
import com.example.demo.utils.CommonRetumType;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.error.BusinessException;
import com.example.demo.utils.error.EmBusinessError;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/user")
//处理跨域CrossOrigin
@CrossOrigin
public class UserController extends BaseController{
    @Autowired
    Userserviceimpl userserviceimpl;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Autowired
    RedisUtil redisUtil;

//    @PostMapping("/getotp")
//    @ResponseBody
//    public CommonRetumType getOtp(@RequestParam(name = "telphone") String telphone)
//    {
//        //生成随机认证码
//        Random random = new Random();
//        int randomint = random.nextInt(99999);
//        randomint+=10000;
//        String otpCode = String.valueOf(randomint);
//        //随机验证码通过httpsession绑定手机号
//        httpServletRequest.getSession().setAttribute(telphone,otpCode);
//
//        return CommonRetumType.create(null);
//    }

//    用户列表查询
    @GetMapping("/index")
    @Role(roles = {"2,3"})
    public CommonRetumType findall()
    {
        Object users = userserviceimpl.findall();
        return CommonRetumType.create(users);
    }

//    单用户查询
    @GetMapping("/findid{id}")
    public CommonRetumType findid(@RequestParam("id") Integer id) throws BusinessException {
        User user = userserviceimpl.findeid(id);
        if (user == null)
        {
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }else {
            return CommonRetumType.create(user);
        }
    }

//    用户添加
    @GetMapping("/create")
    public CommonRetumType create(User user) throws BusinessException {
        Integer user1 = userserviceimpl.insert(user);
        return CommonRetumType.create(user1);
    }


// 指定用户id更新
    @PutMapping
    public CommonRetumType update(User user) throws BusinessException {
        Integer userupdate = userserviceimpl.updateByPrimaryKeySelective(user);
        return CommonRetumType.create(userupdate);

    }
//    删除用户
    @DeleteMapping("/delete{id}")
    public CommonRetumType delete(@RequestParam("id") Integer id)
    {
        Integer userdelete = userserviceimpl.deleteByPrimaryKey(id);
        return CommonRetumType.create(userdelete);
    }
}

